"""
认证缓存模型
"""
from datetime import datetime, timedelta
from ..models.base import db
import json

class AuthCache(db.Model):
    """认证缓存表"""
    id = db.Column(db.Integer, primary_key=True)
    environment_id = db.Column(db.Integer, db.ForeignKey('environment.id'), nullable=False)
    auth_data = db.Column(db.Text)  # 认证数据，JSON格式
    created_at = db.Column(db.DateTime, default=datetime.now)
    expires_at = db.Column(db.DateTime)  # 过期时间
    is_valid = db.Column(db.Boolean, default=True)  # 是否有效
    
    # 关系
    environment = db.relationship('Environment', back_populates='auth_caches')
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'environment_id': self.environment_id,
            'auth_data': json.loads(self.auth_data) if self.auth_data else {},
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'expires_at': self.expires_at.strftime('%Y-%m-%d %H:%M:%S') if self.expires_at else None,
            'is_valid': self.is_valid
        }